<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="50%">
    <el-form
      ref="formRef"
      :model="formData"
      label-width="100px"
      v-loading="formLoading"
    >
      <div style="padding: 8px 0; background: #f8fbff">
        <el-button type="primary" plain @click="openUserForm()">
          选择公函人员
        </el-button>
        <el-table ref="multipleTableRef" :data="tableUserData" style="width: 100%; margin-top: 10px; height: 200px;">
          <el-table-column label="序号" type="index"  header-align="center" align="center" width="60px" fixed />
          <el-table-column label="用户昵称" align="center" prop="nickname" :show-overflow-tooltip="true" />
          <el-table-column label="部门" align="center" key="deptName" prop="deptName" :show-overflow-tooltip="true">
            <template #default="scope">
              {{ deptList.find((dept) => dept.id === scope.row.deptId)?.name }}
            </template>
          </el-table-column>
          <el-table-column label="手机号码" align="center" prop="mobile" width="120" />
          <el-table-column label="操作" align="center" fixed="right" width="140px">
            <template #default="scope">
              <el-button
                size="small"
                link
                type="danger"
                @click.prevent="deleteUserRow(scope.$index, tableUserData)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <!-- 表单弹窗：选择学员 -->
  <SelectUser style="width: 50%" ref="formUserRef" @send-data="updateUserData" />
</template>

<script setup lang="ts">
import { BaseOfficialLetterApi, BaseOfficialLetterDetailsVO } from '@/api/infra/baseofficialletter'
import * as UserApi from '@/api/system/user'
import * as DeptApi from '@/api/system/dept'

import SelectUser from './SelectUser.vue'
import { CommonStatusEnum } from '@/utils/constants'

/** 公函 表单 */
defineOptions({ name: 'BaseOfficialLetterForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const tableUserData = ref<UserApi.UserVO[]>([])
const userList = ref<any>([]) // 线索id
const deptList = ref<any>([])
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formRef = ref() // 表单 Ref
const formData = ref({
  id: undefined,
  officialLetterId: undefined,
  detailData: undefined,
  status: CommonStatusEnum.ENABLE
})

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = "选择人员"
  resetForm()
  // 修改时，设置数据
  if (id) {
    formData.value.officialLetterId = id
    formLoading.value = true
    try {
      tableUserData.value = await BaseOfficialLetterApi.getLetterUserList(id)
    } finally {
      formLoading.value = false
    }
    deptList.value = await DeptApi.getSimpleDeptList()
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 添加/修改操作 */
const formUserRef = ref()
const openUserForm = () => {
  formUserRef.value.open()
}

const receivedUserData = ref('')
const updateUserData = async (data) => {
  receivedUserData.value = data
  if (data) {
    for (let i = 0; i < data.value.length; i++) {
      const index = tableUserData.value.filter((item) => item.id === data.value[i].id)
      if (index.length > 0) {
        message.warning('【'+data.value[i].nickname + '】该人员已添加')
      } else {
        tableUserData.value.push(data.value[i])
      }
    }
  }
}

const deleteUserRow = (index, rows) => {
  rows.splice(index, 1)
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // formData.fileExists
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  userList.value = []
  for (let i = 0; i < tableUserData.value.length; i++) {
    const UserCourse = {
      userId: tableUserData.value[i].id,
      userName: tableUserData.value[i].nickname,
      status: CommonStatusEnum.ENABLE,
      totalViewNum: CommonStatusEnum.ENABLE
    }
    userList.value.push(UserCourse)
  }
  try {
    const data = formData.value as unknown as BaseOfficialLetterDetailsVO
    data.detailData = userList.value
    
    await BaseOfficialLetterApi.updateOfficialDetail(data)
    message.success(t('common.updateSuccess'))
      
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    officialLetterId: undefined,
    detailData: undefined,
    status: CommonStatusEnum.ENABLE
  }
  formRef.value?.resetFields()
}
</script>